<template>
  <div>
    <el-dialog
      title="新增楼层"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addInfo"
        :rules="rules"
        ref="refAddInfo"
        label-width="100px"
      >
        <el-form-item size="small">
          <el-radio v-model="radio" label="1">单个添加楼层</el-radio>
          <el-radio v-model="radio" label="2" style="margin-left: 20px"
            >批量添加楼层</el-radio
          >
        </el-form-item>
        <!-- <el-form-item size="small" label="楼层名称" prop="name">
          <el-input clearable v-model.trim="addInfo.name" placeholder="请输入楼层名称"></el-input>
        </el-form-item> -->

        <!-- <el-form-item size="small" label="布防状态" prop="isDefence">
          <el-select v-model="addInfo.isDefence" placeholder="请选择布防状态" style="width: 360px">
            <el-option v-for="item in isDefenceArr" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item size="small" label="组织机构" prop="orgId">
          <el-select
            v-model="addInfo.orgId"
            filterable
            placeholder="请选择组织机构"
            style="width: 360px"
            class="elSelect"
            @change="projectchange"
            v-loadMore="loadMore"
          >
            <el-option
              v-for="(item, i) in projectList"
              :key="i"
              :label="item.orgName"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item size="small" label="建筑物" prop="pid">
          <el-select
            v-model="addInfo.pid"
            filterable
            placeholder="请选择建筑物"
            style="width: 360px"
            v-loadMore="loadMore2"
          >
            <el-option
              v-for="item in buildings"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item
          size="small"
          label="楼层名称"
          prop="floorName"
          v-if="radio == '1'"
        >
          <div style="display: flex; justify-content: space-between">
            <el-input
              clearable
              v-model="addInfo.floorName"
              maxlength="2"
              placeholder="请输入楼层名称"
              oninput="{ value=value.replace(/[^\-\d]/g, '') } { value=value.replace(/\-{2,}/g, '-') } { value=value.replace(/(\d)\-/g, '$1') }
            { value=value.replace(/-(0+)/g, '0') } { value=value.replace(/^0+(\d)/, '$1') }
          {if(value<-3)value=-3} {if(value=='0')value=1} {if(value=='-0')value=-1} {if(value>50)value=50}"
            ></el-input>
            <span style="margin-left: 5px" class="ceng">层</span>
          </div>
        </el-form-item>

        <el-form-item
          size="small"
          :label="index == 0 ? '楼层' : ''"
          v-for="(domain, index) in addInfo.floorsId"
          :key="domain.key"
          :prop="'floorsId.' + index + '.id2'"
          :rules="{
            required: true,
            message: '楼层数不能为空',
            trigger: 'blur',
          }"
          v-show="radio == '2'"
        >
          <div style="display: flex; justify-content: space-between">
            <!-- oninput="if(isNaN(value)) { value = null } {if(value>49)value=49}" -->
            <el-input
              type="input"
              maxlength="2"
              v-model.trim="domain.id1"
              style="width: 30%"
              :placeholder="index == 0 ? '1' : ''"
              oninput=" { value=value.replace(/[^\-\d]/g, '') } { value=value.replace(/\-{2,}/g, '-') } { value=value.replace(/(\d)\-/g, '$1') }
            { value=value.replace(/-(0+)/g, '0') } { value=value.replace(/^0+(\d)/, '$1') }
            {if(value<-3)value=-3} {if(value=='0')value=1} {if(value=='-0')value=-1} {if(value>49)value=49}"
            >
            </el-input>
            至
            <el-input
              type="input"
              style="width: 30%"
              maxlength="2"
              v-model.trim="domain.id2"
              :placeholder="index == 0 ? '5' : ''"
              oninput="{ value=value.replace(/[^\-\d]/g, '') } { value=value.replace(/\-{2,}/g, '-') } { value=value.replace(/(\d)\-/g, '$1') }
            { value=value.replace(/-(0+)/g, '0') } { value=value.replace(/^0+(\d)/, '$1') }
             {if(value<-3)value=-3} {if(value=='0')value=1} {if(value=='-0')value=-1} {if(value>50)value=50}"
            ></el-input>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="bottom"
              >
                <i
                  class="el-icon-remove-outline zuobiao2"
                  style="font-size: 20px; cursor: pointer"
                  @click.prevent="removeFloor(domain)"
                ></i>
              </el-tooltip>
            </div>
            <!-- <el-button size="mini" @click.prevent="removeFloor(domain)" type="danger">删除</el-button> -->
          </div>
        </el-form-item>

        <el-form-item
          size="small"
          v-show="this.addInfo.floorsId.length < 2 && radio == '2'"
        >
          <el-tooltip
            class="item"
            effect="dark"
            content="新增楼层"
            placement="bottom"
          >
            <i
              class="el-icon-circle-plus-outline zuobiao2"
              style="font-size: 20px; cursor: pointer"
              @click="addFloor"
            ></i>
          </el-tooltip>
          <!-- <el-button size="small" @click="addFloor" type="primary">新增</el-button> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqOrgList,
  reqFloorAdd,
  reqBatchAdd,
  reqSpaceManager,
} from "@/api/api";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import { mapState } from "vuex";
import { handleTree } from "@utils/trans-tree";
import loadMore from "@mixin/loadMore";

export default {
  name: "add",
  components: { treeselect },
  // props: ["buildings"],
  mixins: [loadMore],
  data() {
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      radio: "1",
      buildings: [],
      projectList: [], //组织机构数据
      dialogVisible: false,
      addInfo: {
        orgId: "",
        floorName: "",
        childrenName: [],
        name: "",
        isDefence: "",
        buildingType: "2",
        floorsId: [
          {
            id1: "1",
            id2: "5",
          },
        ],
        pid: "",
      },
      isDefenceArr: [
        {
          id: "0",
          label: "撤防",
        },
        {
          id: "1",
          label: "布防",
        },
      ],
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入楼层名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        floorName: [
          {
            required: true,
            message: "请输入楼层名称",
            trigger: "blur",
          },
        ],
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: "change",
          },
        ],
        pid: [
          {
            required: true,
            message: "请选择建筑物",
            trigger: "change",
          },
        ],
        isDefence: [
          {
            required: true,
            message: "请选择布防状态",
            trigger: "change",
          },
        ],
      },
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    radio(e) {
      this.$refs.refAddInfo.resetFields();
    },
  },
  methods: {
    // 在 Input 值改变时触发
    handleEdit(e, index) {
      console.log(this.addInfo.floorsId[index].id1, e, index);
      let value = e.replace(/[^d]/g, ""); // 只能输入数字
      value = value.replace(/^0+(d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
      value = value.replace(/(d{15})d*/, "$1"); // 最多保留15位整数
      this.addInfo.floorsId[index].id1 = value;
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.OrgList();
      this.loading = false;
    },
    // 获取组织机构列表
    async OrgList() {
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.projectList = res.data.rows
    },
    // 根据组织机构查询建筑物
    projectchange(e) {
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = [];
      this.addInfo.pid = "";
      this.SpaceManager();
    },
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.SpaceManager();
      this.loading2 = false;
    },
    // 建筑物列表
    async SpaceManager() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 1,
        orgId: this.addInfo.orgId,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.buildings = [...this.buildings, ...res.data.rows];
    },

    removeFloor(item) {
      // console.log(item);
      // console.log(this.addInfo.floorsId.length);
      if (this.addInfo.floorsId.length == 1) return;
      var index = this.addInfo.floorsId.indexOf(item);
      if (index !== -1) {
        this.addInfo.floorsId.splice(index, 1);
      }
    },
    addFloor() {
      this.$notify.closeAll();
      // if (this.addInfo.floorsId.length > 1) return this.$modal.notifyWarning('最多只允许添加两个楼层信息');
      this.addInfo.floorsId.push({
        id1: "",
        id2: "",
        key: Date.now(),
      });
    },
    editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          if (this.radio == "1") {
            const res2 = await reqFloorAdd({
              pid: this.addInfo.pid,
              name: this.addInfo.floorName + "层",
            });
            if (res2.code !== 20000)
              return this.$modal.notifyWarning(res2.message);
          } else {
            let arr = [];
            let flag = false;
            let index = 0;
            let flag2 = false;
            this.addInfo.floorsId.forEach((item, i) => {
              // console.log(item);
              if (item.id1 == "" || item.id2 == "") {
                flag2 = true;
                return;
              }
              if (item.id1 > item.id2) {
                index = i + 1;
                flag = true;
                return;
              }
              for (let i = item.id1; i <= item.id2; i++) {
                // console.log(i);
                if (i != "") {
                  arr.push(`${i}层`);
                }
              }
            });
            if (flag2) return this.$modal.notifyWarning("楼层数不能为空");
            //  if (flag) return this.$modal.notifyWarning(`第${index}项结束楼层小于开始楼层，请检查！`)
            let nameList = Array.from(new Set(arr));
            // console.log(nameList);
            if (nameList.length == 0)
              return this.$modal.notifyWarning("楼层名称不能为空");
            const res2 = await reqBatchAdd({
              pid: this.addInfo.pid,
              nameList: nameList,
            });
            if (res2.code !== 20000)
              return this.$modal.notifyWarning(res2.message);
          }
          // 组织机构||园区
          // if (
          //   this.user.roleName == "ORG_ADMIN" ||
          //   this.user.roleName == "PARK_ADMIN"
          // ) {
          //   this.addInfo.orgId = this.user.orgId; // 组织机构id
          // }
          // const res = await reqAdd(this.addInfo);
          // if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加楼层成功");
          this.closeEditDialog();
          this.$parent.SpaceManager(); //更新建筑物列表
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.$refs.refAddInfo.resetFields();
      this.radio = "1";
      this.projectList = [];
      this.buildings = [];
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.addInfo = {
        orgId: "",
        floorName: "",
        childrenName: [],
        name: "",
        isDefence: "",
        buildingType: "2",
        floorsId: [
          {
            id1: "1",
            id2: "5",
          },
        ],
        pid: "",
      };
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if(this.$refs.refAddInfo!=null){
      this.closeEditDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

.zuobiao2 {
  color: @primaryTxtcolor;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束
::v-deep .el-radio {
  color: @primaryThemeTxtColor2;
}
::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #7367f0;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}
.ceng {
  color: @primaryThemeTxtColor2;
}
</style>